import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import Far from './components/Far'
export default class App extends Component {
  componentDidMount() {
    // 一般在组件挂载之后订阅
    this.token = PubSub.subscribe('xxx', (topic, data) => {
      console.log('xxx话题', data)
    })
    this.yToken = PubSub.subscribe('yyy', (topic, data) => {
      console.log('yyy话题', data)
    })
  }

  // 注意: 虽然此时功能已经实现,但是性能不好.因为如果组件卸载了,但是pubsub中跟当前组件相关的订阅还存在在内存中.所以我们需要在组件卸载的时候,清除订阅
  componentWillUnmount() {
    PubSub.unsubscribe(this.token)
    PubSub.unsubscribe(this.yToken)
  }
  render() {
    return (
      <div>
        <div>
          <button
            onClick={() => {
              PubSub.unsubscribe(this.token)
            }}
          >
            清除app组件中xxx话题
          </button>
          <button
            onClick={() => {
              PubSub.unsubscribe('xxx')
            }}
          >
            清除xxx所有话题
          </button>
          <button
            onClick={() => {
              PubSub.clearAllSubscriptions()
            }}
          >
            清除所有话题
          </button>
        </div>
        <hr />
        App
        <hr />
        <Far></Far>
      </div>
    )
  }
}
